Skip to content

Create 1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js #3972

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

aadil42
Copy link
Contributor

@aadil42 aadil42 commented Mar 29, 2025

Solved number-of-ways-to-stay-in-the-same-place-after-some-steps

File(s) Added: 1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.js
Language(s) Used: JavaScript
Submission URL : https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/submissions/1589993538/

Solved number-of-ways-to-stay-in-the-same-place-after-some-steps
@@ -0,0 +1,29 @@
/**
* DP | Recursion
* Time O(n^2) | Space O(n^2)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can reduce space

/**
 * DP - Bottom Up
 * Array - Tabulation
 * Time O(N * MIN(N, M)) | Space O(MIN(N, M))
 * @param {number} steps
 * @param {number} arrLen
 * @return {number}
 */
var numWays = (steps, arrLen) => {
    const mod = ((10 ** 9) + 7);
    const length = Math.min(((steps >> 1) + 1), arrLen);

    let tabu = initTabu(length);
    tabu[1] = 1;

    for (let step = steps; (0 < step); step--) {
        const prev = initTabu(length);

        for (let pos = 1; (pos <= length); pos++) {
            prev[pos] = (
                tabu[pos - 1]
                + tabu[pos]
                + tabu[pos + 1]
            ) % mod;
        }

        tabu = prev;
    }

    return tabu[1];    
};

var initTabu = (length) => new Array(length + 2).fill(0);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants